<?php

namespace app\index\controller;

use think\Request;
use app\index\model\User as UserModel;
use app\index\model\Topic as TopicModel;
use app\index\model\Reply as ReplyModel;

class User extends Core
{
    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(Request $request, $id)
    {
        $user = UserModel::find($this->current_user->id);
        $this->assign('user', $user);

        $param_tab = $request->param('tab');
        if($param_tab == 'replies'){
            $is_replies = true;
            $reply_paginate = ReplyModel::minePaginate(['user_id' => $user->id], 5);
            $this->assign('reply_paginate', $reply_paginate);
        }else{
            $is_replies = false;
            $topic_paginate = TopicModel::minePaginate(['user_id' => $user->id], 5);
            $this->assign('topic_paginate', $topic_paginate);
        }

        $this->assign('is_replies', $is_replies);
        return $this->fetch('read');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        if($id != $this->current_user->id){
            $this->redirect(url('root'));
        }

        $user = UserModel::find($id);
        if(empty($user)){
            $this->redirect(url('root'));
        }
        $this->assign('user', $user);
        return $this->fetch('edit');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if(!$request->isAjax()){
            $this->redirect('user/read', ['id' => $id]);
        }

        if($id != $this->current_user->id){
            $this->error('对不起，您不能访问当前页面', url('root'));
        }

        $user = UserModel::find($id);
        if(empty($user)){
            $this->error('对不起，您不能访问当前页面', url('root'));
        }

        $data = $request->post();
        $result = $user->updateInfo($data);
        if($result->status){
            $this->success($result->message, url('user/read', ['id' => $user_id]));
        }else{
            $this->error($result->message);
        }
    }
}
